<template>
  <div class="account-page page-container">
    <!-- 内容区域 -->
    <div class="content">
      <!-- 账户余额卡片 -->
      <div class="balance-card">
        <div class="balance-header">
          <span class="label">账户余额</span>
          <a-button type="primary" @click="showRechargeModal">充值</a-button>
        </div>
        <div class="balance-amount">
          <span class="currency">￥</span>
          <span class="amount">{{ accountInfo.balance }}</span>
        </div>
        <div class="balance-details">
          <div class="detail-item">
            <span class="label">总充值</span>
            <span class="value">￥{{ accountInfo.totalRecharge }}</span>
          </div>
          <div class="detail-item">
            <span class="label">已消费</span>
            <span class="value">￥{{ accountInfo.totalConsumption }}</span>
          </div>
        </div>
      </div>

      <!-- 充值记录 -->
      <div class="record-section">
        <div class="section-header">
          <span class="title">充值记录</span>
        </div>
        <a-table
          :columns="columns"
          :data-source="rechargeRecords"
          :loading="loading"
          :pagination="pagination"
          @change="handleTableChange"
          :scroll="{ x: 'max-content' }"
          rowKey="id"
          size="middle"
        >
          <!-- 支付方式列 -->
          <template #payMethod="{ text }">
            <span class="pay-method">
              <a-icon :type="getPayMethodIcon(text)" />
              {{ getPayMethodText(text) }}
            </span>
          </template>

          <!-- 状态列 -->
          <template #status="{ text }">
            <a-tag :color="getStatusColor(text)" style="color: #fff">
              {{ getStatusText(text) }}
            </a-tag>
          </template>

          <!-- 操作列 -->
          <!-- <template #action="{ record }">
            <a @click="showReceiptDetail(record)">查看凭证</a>
          </template> -->
        </a-table>
      </div>
    </div>

    <!-- 充值弹窗 -->
    <a-modal
      v-model="rechargeVisible"
      title="账户充值"
      @ok="handleRecharge"
      :confirmLoading="rechargeLoading"
    >
      <div class="recharge-form">
        <div class="amount-options">
          <a-radio-group v-model="selectedAmount">
            <a-radio-button
              v-for="amount in rechargeAmounts"
              :key="amount"
              :value="amount"
            >
              {{ amount }}元
            </a-radio-button>
          </a-radio-group>
        </div>
        <div class="custom-amount">
          <a-input-number
            v-model="customAmount"
            :min="1"
            :max="99999"
            placeholder="其他金额"
            style="width: 100%"
          />
        </div>
      </div>
    </a-modal>

    <!-- 添加凭证详情弹窗 -->
    <!-- <a-modal v-model="receiptVisible" title="充值凭证" :footer="null">
      <div class="receipt-detail" v-if="currentReceipt">
        <p>订单号：{{ currentReceipt.orderNo }}</p>
        <p>充值金额：￥{{ (currentReceipt?.amount || 0).toFixed(2) }}</p>
        <p>支付方式：{{ getPayMethodText(currentReceipt.payMethod) }}</p>
        <p>充值时间：{{ currentReceipt.time }}</p>
        <p>交易状态：{{ getStatusText(currentReceipt.status) }}</p>
      </div>
    </a-modal> -->
  </div>
</template>

<script>
import {
  Layout,
  Button,
  Icon,
  Table,
  Tag,
  Modal,
  Radio,
  InputNumber,
  message,
} from "ant-design-vue";
import { getUserRecharge, getUserAccount, addUserRecharge } from "@/api/user";
import { mapGetters } from "vuex";
import moment from "moment";

export default {
  name: "AccountInfo",
  components: {
    AButton: Button,
    AIcon: Icon,
    ATable: Table,
    ATag: Tag,
    AModal: Modal,
    ARadioGroup: Radio.Group,
    ARadioButton: Radio.Button,
    AInputNumber: InputNumber,
  },
  computed: {
    ...mapGetters("user", ["id", "account"]),
  },
  data() {
    return {
      loading: false,
      columns: [
        {
          title: '充值金额',
          dataIndex: 'amount',
          key: 'amount',
          align: 'center',
          width: 100
        },
        {
          title: '充值时间',
          dataIndex: 'createTime',
          key: 'createTime',
          width: 180,
          customRender: (text) => {
            return text ? moment(text).format('YYYY-MM-DD HH:mm:ss') : '-'
          }
        },
        {
          title: '状态',
          dataIndex: 'status',
          key: 'status',
          scopedSlots: { customRender: 'status' },
          width: 100,
          align: 'center'
        },
        {
          title: '描述',
          dataIndex: 'description',
          key: 'description',
          width: 200,
          ellipsis: true
        }
      ],
      pagination: {
        current: 1,
        pageSize: 10,
        total: 0,
        showSizeChanger: true,
        showQuickJumper: true,
        showTotal: (total) => `共 ${total} 条记录`,
      },
      accountInfo: {
        balance: 0,
        totalRecharge: 0,
        totalConsumption: 0,
      },
      rechargeRecords: [],
      rechargeVisible: false,
      rechargeLoading: false,
      selectedAmount: 100,
      customAmount: null,
      rechargeAmounts: [50, 100, 200, 500, 1000],
      // receiptVisible: false,
      // currentReceipt: null,
    };
  },
  created() {
    this.fetchAccountInfo();
    this.fetchRechargeRecords();
  },
  methods: {
    async fetchAccountInfo() {
      try {
        const response = await getUserAccount();
        if (response && response.code === 200) {
          this.accountInfo = {
            balance: response.data.balance || 0,
            totalRecharge: response.data.totalRecharge || 0,
            totalConsumption: response.data.totalConsumption || 0,
          };
        } else {
          throw new Error(response?.msg || "获取账户信息失败");
        }
      } catch (error) {
        message.error(error.message || "获取账户信息失败");
      }
    },
    async fetchRechargeRecords() {
      this.loading = true;
      try {
        const params = {
          pageNo: this.pagination.current,
          pageSize: this.pagination.pageSize,
        };
        const response = await getUserRecharge(params);
        if (response && response.code === 200) {
          this.rechargeRecords = (response.data.data || []).map((record) => ({
            ...record,
            amount: record.amount || 0,
            status: record.status || 0,
            createTime: record.createTime || "",
            description: record.description || "",
          }));
          this.pagination.total = response.data.totalCount || 0;
        } else {
          throw new Error(response?.msg || "获取充值记录失败");
        }
      } catch (error) {
        message.error(error.message || "获取充值记录失败");
      } finally {
        this.loading = false;
      }
    },
    handleTableChange(pagination) {
      this.pagination = { ...this.pagination, ...pagination };
      this.fetchRechargeRecords();
    },
    getStatusColor(status) {
      const colors = {
        0: '#faad14',    // 待审核 - 橙色
        1: '#52c41a',    // 已审核 - 绿色
        2: '#f5222d'     // 拒绝 - 红色
      }
      return colors[status] || '#d9d9d9'
    },
    getStatusText(status) {
      const texts = {
        0: "待审核",
        1: "已审核",
        2: "拒绝",
      };
      return texts[status] || "待审核";
    },
    showRechargeModal() {
      this.rechargeVisible = true;
      this.selectedAmount = 100;
      this.customAmount = null;
    },
    async handleRecharge() {
      const amount = this.customAmount || this.selectedAmount;
      if (!amount) {
        message.warning("请选择或输入充值金额");
        return;
      }

      this.rechargeLoading = true;
      try {
        const params = {
          userId: this.id,
          account: this.account,
          amount: amount,
        };
        const response = await addUserRecharge(params);
        if (response && response.code === 200) {
          message.success("充值成功，待审核");
          this.rechargeVisible = false;
          // 刷新账户信息和充值记录
          await this.fetchAccountInfo();
          await this.fetchRechargeRecords();
        } else {
          throw new Error(response?.msg || "充值失败");
        }
      } catch (error) {
        message.error(error.message || "充值失败，请重试");
      } finally {
        this.rechargeLoading = false;
      }
    },
    getPayMethodIcon(method) {
      const icons = {
        alipay: "alipay-circle",
        wechat: "wechat",
        bank: "bank",
      };
      return icons[method] || "question-circle";
    },
    getPayMethodText(method) {
      const texts = {
        alipay: "支付宝",
        wechat: "微信支付",
        bank: "银行卡",
      };
      return texts[method] || "其他";
    },
    // showReceiptDetail(record) {
    //   this.currentReceipt = record;
    //   this.receiptVisible = true;
    // },
  },
};
</script>

<style lang="less" scoped>
.account-page {
  min-height: 100vh;
  background: #f5f7fa;
  padding-top: 0;
  position: relative;
  z-index: 1;

  .content {
    padding: 16px;
    margin-top: 0;

    .balance-card {
      background: linear-gradient(135deg, #1890ff, #096dd9);
      border-radius: 12px;
      padding: 20px;
      color: #fff;
      margin-bottom: 16px;

      .balance-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: 16px;

        .label {
          font-size: 16px;
        }
      }

      .balance-amount {
        margin-bottom: 20px;

        .currency {
          font-size: 20px;
          margin-right: 4px;
        }

        .amount {
          font-size: 32px;
          font-weight: 500;
        }
      }

      .balance-details {
        display: flex;
        gap: 24px;

        .detail-item {
          .label {
            font-size: 12px;
            opacity: 0.8;
            margin-bottom: 4px;
          }

          .value {
            font-size: 16px;
            font-weight: 500;
          }
        }
      }
    }

    .record-section {
      background: #fff;
      border-radius: 8px;
      padding: 16px;
      margin-top: 16px;

      .section-header {
        margin-bottom: 16px;

        .title {
          font-size: 16px;
          font-weight: 500;
          color: #262626;
        }
      }

      :deep(.ant-table) {
        .amount-cell {
          .prefix {
            color: #52c41a;
            margin-right: 2px;
          }
        }

        .pay-method {
          display: flex;
          align-items: center;
          gap: 4px;

          .anticon {
            font-size: 16px;
          }
        }
      }
    }
  }
}

.recharge-form {
  .amount-options {
    margin-bottom: 16px;
    text-align: center;

    .ant-radio-group {
      display: grid;
      grid-template-columns: repeat(3, 1fr);
      gap: 8px;
    }
  }

  .custom-amount {
    padding: 0 40px;
  }
}

@media screen and (max-width: 768px) {
  .account-page {
    .content {
      padding: 12px;
      height: calc(100vh - 50px);

      .balance-card {
        padding: 16px;

        .balance-amount {
          .amount {
            font-size: 28px;
          }
        }
      }

      .record-section {
        padding: 12px;
        margin-top: 12px;

        :deep(.ant-table) {
          font-size: 13px;

          .ant-table-thead > tr > th,
          .ant-table-tbody > tr > td {
            padding: 8px;
          }
        }
      }
    }
  }

  .recharge-form {
    .amount-options {
      .ant-radio-group {
        grid-template-columns: repeat(2, 1fr);
      }
    }
  }
}

.receipt-detail {
  padding: 12px;

  p {
    margin-bottom: 12px;
    line-height: 1.5;
    color: #262626;

    &:last-child {
      margin-bottom: 0;
    }
  }
}
</style>
